<script lang="ts" setup>
import { reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { ApiLogin, ApiGetUserInfo, ApiRefreshVerifyCode } from '@/services/apis/user'
import { useUserStore as useOldUserStore } from '@/store'
import { useNotification } from '@/hooks/useNotification'
import { useUserStore } from '@/stores/user.store'

const verifyCodeBase64 = reactive({
  verifyCodeSvg: '',
  uuid: ''
})
const updateVerifyCode = (uuid: string, verifyCodeSvg: string) => {
  verifyCodeBase64.verifyCodeSvg = verifyCodeSvg ?? verifyCodeBase64.verifyCodeSvg
  verifyCodeBase64.uuid = uuid ?? verifyCodeBase64.uuid
}

const router = useRouter()
const loginForm = reactive({
  username: '',
  password: '',
  verifyCode: ''
})
const { t } = useI18n()
const { Notification } = useNotification()
const userOldStore = useOldUserStore()
const { getUserInfo } = useUserStore()
async function handleLogin() {
  if (!loginForm.username || !loginForm.password) {
    return Notification.error({
      content: t('login.form.empty')
    })
  } else if (verifyCodeBase64.uuid && (loginForm.verifyCode.length != 4 || !loginForm.verifyCode)) {
    return Notification.error({
      content: t('login.form.error.verifyCode')
    })
  }
  const { username, password, verifyCode } = loginForm
  const { data = {}, status } = await ApiLogin(
    username,
    password,
    verifyCode,
    verifyCodeBase64.uuid
  )
  const { access_token: token, verifyCodeSvg, uuid } = data
  updateVerifyCode(uuid, verifyCodeSvg)
  loginForm.verifyCode = ''

  if (token) {
    localStorage.setItem('token', token)
    const userInfo = await ApiGetUserInfo()
    getUserInfo(token)
    userOldStore.setUserInfo({
      name: userInfo.user,
      uid: userInfo.uid,
      avatar:
        userInfo?.avatar ??
        'https://qingshaner.oss-cn-hangzhou.aliyuncs.com/images/202209252035100.jpg',
      token
    })
    Notification.success({
      content: t('login.form.success')
    })
    return await router.push('/')
  } else if (status === 401) {
    Notification.error({
      content: t('login.form.error')
    })
  } else if (status == 429) {
    Notification.error({
      content: t('login.form.error.requestMuch')
    })
  } else {
    Notification.error({
      content: t('login.form.error.verifyCode')
    })
  }
}

const toggleCard = defineEmits(['toggle'])
function handleRegister() {
  toggleCard('toggle')
}

async function handleRefreshVerifyCode() {
  const { status, uuid, verifyCodeSvg } = await ApiRefreshVerifyCode(verifyCodeBase64.uuid)
  if (status === 429) {
    return Notification.error({
      content: t('login.form.error.requestMuch')
    })
  }
  updateVerifyCode(uuid, verifyCodeSvg)
}
</script>

<template>
  <div shadow="gray-300 dark:gray-600 2xl" text="center" bg="light-900 dark:gray-800">
    <h2 class="text-2xl font-bold font-serif">{{ $t('login.title') }}</h2>
    <div
      class="ml-3 h-50 after:(left-1/5 z-0 h-25 w-25 from-[#70ce49] to-[#fea92e] blur-xl content-[''] -top-4/5)"
      after:transition="margin duration-500 ease-in-out"
      after:bg="gradient-to-b"
      after:relative
      after:block
      after:rounded-full
    >
      <img src="/plants/1.svg" class="relative z-1 !h-50" />
    </div>
    <form flex="~ col" class="gap-4">
      <a-input v-model="loginForm.username" autocomplete :placeholder="$t('login.username')">
        <template #prefix>
          <IconUser />
        </template>
      </a-input>
      <a-input-password
        v-model="loginForm.password"
        autocomplete
        :placeholder="$t('login.password')"
      >
        <template #prefix>
          <IconLock />
        </template>
      </a-input-password>
      <a-input-search
        v-if="verifyCodeBase64.verifyCodeSvg"
        v-model="loginForm.verifyCode"
        class="verify-input"
        :placeholder="$t('login.form.verifyCode')"
        search-button
        @search="handleRefreshVerifyCode()"
      >
        <template #prefix>
          <IconRobot />
        </template>
        <template #button-icon>
          <p class="inline-block flex-1 overflow-hidden rounded-r-sm">
            <img :src="verifyCodeBase64.verifyCodeSvg" />
          </p>
        </template>
      </a-input-search>
      <button
        type="button"
        class="rounded-full text-[1.1rem] font-bold transition"
        bg="orange-300 hover:orange-200 active:orange-100"
        dark:bg="blue-gray-700 hover:blue-gray-900 active:blue-gray-800"
        p="y-2 x-8"
        @click="handleLogin"
      >
        {{ $t('login.submit') }}
      </button>
      <button
        type="button"
        class="rounded-full text-[1.1rem] font-bold transition"
        bg="gray-100 hover:gray-200 active:gray-100"
        dark:bg="blue-gray-700 hover:blue-gray-900 active:blue-gray-800"
        p="y-2 x-8"
        @click="handleRegister"
      >
        {{ $t('login.register') }}
      </button>
    </form>
  </div>
</template>

<style lang="css" scoped>
:deep(.verify-input > .arco-input-wrapper) {
  @apply w-[138.4px];
}

:deep(.arco-btn-size-medium.arco-btn-only-icon) {
  @apply bg-orange-400 border-0 w-24 hover:bg-orange-200 active:bg-orange-100;
  @apply dark:(bg-blue-gray-700 hover:bg-blue-gray-900 active:bg-blue-gray-800);
}
</style>
